<?php

use App\Model\UserUp;
use App\User;
use Illuminate\Database\Seeder;

class UserUpTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     * 将会员无限极关系瓶装成字符串;如 1,2,3,4
     * @return void
     */
    public function run()
    {
        $user =  User::select("id", "pid")->whereIn('type', [3,4])->get()->toArray();
        $tree = $this->getTree($user, ['id' => '', 'user_up_list'=>'']);

        foreach ($tree as $k => $v){
            $userUp= new UserUp();
            $userUp->user_id = $v['id'];
            $userUp->user_up_list = $v['user_up_list'];
            $save = $userUp->save();
            if ($save) {
                echo $v['id'] ." - ok\n";
            }else{
                echo $v['id'] ." - false\n";
            }
        }
        echo "完成";
    }

    public function getTree(&$data, $d)
    {
        $sign = '';
        foreach($data as $k => $v)
        {
            if($v['pid'] == $d['id'])
            {        //父亲找到儿子

                if ($v['pid'] !=0) {
                    $sign = ',';
                }
                $v['user_up_list'] = $v['pid'] . $sign . $d['user_up_list'];
                $data[$k]['user_up_list'] = $v['pid'] . $sign . $d['user_up_list'];
                $this->getTree($data, $v);
            }
        }

        return $data;
    }
}
